package com.psq.core.common.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.get
import com.alibaba.android.arouter.launcher.ARouter
import com.psq.core.common.R
import com.saicmotor.core.common.utils.isNull

abstract class BaseActivity: AppCompatActivity(), IPattern {

    private var isDestroy = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isDestroy = false
        doBeforeView(savedInstanceState)
        setContentView(getLayoutResId())
        initStatusBar()
        initView(savedInstanceState)
        doAfterView(savedInstanceState)
    }


    override fun doBeforeView(savedInstanceState: Bundle?) {
        if (enableAutowired()) ARouter.getInstance().inject(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
    }

    override fun doAfterView(savedInstanceState: Bundle?) {
    }

    /**
     * 注意如果当前[BaseActivity]中包含[BaseFragment], 此组件无效,
     * 请使用Fragment的[BaseFragment.mProgressBar]
     */
    open val mProgressBar: ProgressBar?
        get() {
            if (supportFragmentManager.fragments.isNotEmpty()) return null
            val progressBar = findViewById<ProgressBar?>(R.id.progress_bar)
            return if (progressBar.isNull()) {
                val parent =
                    window.decorView.findViewById<ViewGroup>(android.R.id.content)[0] as? ViewGroup
                LayoutInflater.from(this)
                    .inflate(R.layout.layout_progressbar, parent, true)
                    .findViewById(R.id.progress_bar)
            } else progressBar
        }

    override fun showProgressBar() {
        if (!isProgressBarCancelable())
            window?.setFlags(
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
            )
        mProgressBar?.visibility = View.VISIBLE
    }

    override fun hideProgressBar() {
        if (!isProgressBarCancelable())
            window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
        mProgressBar?.visibility = View.GONE
    }


    open fun enableAutowired() = false


    /**
     * 跟生命周期相关  被销毁则不会执行
     */
    override fun runLifecycleOnUiThread(action: Runnable) {
        if (!isDestroy) {
            runOnUiThread(action)
        }
    }

    override fun initStatusBar() {

    }


    override fun onDestroy() {
        super.onDestroy()
        isDestroy = true
//        RecyclerViewBindingAdapterDestroyUtils.destroyActivity(this)
    }

}